package vip.xiaonuo.core.util;


import okhttp3.*;
import okio.Buffer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;


public class OkHttpInterceptor implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(OkHttpInterceptor.class);

    @Override
    public Response intercept(Chain chain) {
        LocalDateTime start = LocalDateTime.now();
        Response response = null;
        String responseBody = null;
        Integer responseCode = null;
        String url = null;
        String requestBody = null;
        try {
            Request request = chain.request();
            url = request.url().toString();
            requestBody = getRequestBody(request);
            response = chain.proceed(request);
            responseBody = response.body().string();
            responseCode = response.code();
            MediaType mediaType = response.body().contentType();
            response = response.newBuilder().body(ResponseBody.create(mediaType, responseBody))
                    .build();
        } catch (Exception e) {
            log.error("获取请求http报文时发生异常：{}", e.getMessage(), e);
        } finally {
            Duration duration = Duration.between(start, LocalDateTime.now());
            log.debug("Okhttp3 Request Log Start");
            log.debug("请求url：{}", url);
            log.debug("请求报文：{}", requestBody);
            log.debug("响应HTTP状态码：{}", responseCode);
            log.debug("响应报文：{}", responseBody);
            log.debug("耗时：{} 毫秒", duration.toMillis());
            log.debug("Okhttp3 Request Log End");
        }
        return response;
    }

    /**
     * 获取请求报文
     *
     * @param request httpRequest
     * @return body string
     */
    private String getRequestBody(Request request) {
        if (Objects.nonNull(request) && Objects.nonNull(request.body())) {
            try {
                Buffer buffer = new Buffer();
                request.body().writeTo(buffer);
                Charset charset = StandardCharsets.UTF_8;
                return buffer.readString(charset);
            } catch (IOException e) {
                log.error("发送IO异常：{}", e.getMessage(), e);
            }
        }
        return StringUtils.EMPTY;
    }


}
